import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gallery_saver_plus/gallery_saver.dart';
import 'package:im_app/im/util/ImSingleton.dart';
import 'package:loading_indicator/loading_indicator.dart';

import '../../pojo/ImPojo.dart';
import '../bloc/MessageSendCubit.dart';
import '../view/component/UiUtil.dart';

// 拍照
class CaptureImagePage extends StatefulWidget {
  const CaptureImagePage({super.key});

  @override
  State<StatefulWidget> createState() => _CaptureImageState();
}

class _CaptureImageState extends State<CaptureImagePage> {
  CameraController? _cameraController;
  bool _cameraInitialized = false;
  bool _isFlash = false;
  bool _isCaptureImage = true;

  @override
  void initState() {
    super.initState();
    _initCamera();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        top: false,
        bottom: false,
        child: _buildBody(context),
      ),
    );
  }

  Widget _buildBody(BuildContext context) {
    if (_cameraController == null || !_cameraInitialized) {
      return const Center(
        child: LoadingIndicator(indicatorType: Indicator.ballClipRotate),
      ); // 显示加载指示器等
    }
    return _buildCaptureImageView(context);
  }

  Widget _buildCaptureImageView(BuildContext context) {
    return Column(
      children: [
        _buildFlashPane(),
        Expanded(
            child: _cameraController == null ? const Text('') : CameraPreview(_cameraController!,),
        ),
        _buildCaptureControlPane(context),
      ],
    );
  }

  Widget _buildCaptureVideo() {
    return Column(
      children: [],
    );
  }

  // 拍照闪光面板
  Widget _buildFlashPane() {
    var file = _isFlash ? 'assets/img/flash.png' : 'assets/img/flash_close.png';
    return Padding(
      padding: const EdgeInsets.only(left: 20, right: 20, top: 20),
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              setState(() {
                _isFlash = !_isFlash;
              });
            },
            child: Image(
              image: AssetImage(file),
              width: 30,
              height: 30,
            ),
          ),
        ],
      ),
    );
  }

  // 拍照控制面板： 退出，拍照（摄影），切换镜头
  Widget _buildCaptureControlPane(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 20),
      child: Column(
        children: [
          _buildImageAndVideoSwitchPane(),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              GestureDetector(
                  onTap: () {
                    Navigator.of(context).pop();
                  },
                  child: buildSvgView('assets/svg/close.svg', 50, 50, Colors.white)
              ),
              GestureDetector(
                  onTap: () async {
                    var xFile = await _cameraController?.takePicture();
                    if (xFile != null) {
                      await GallerySaver.saveImage(xFile!.path);
                      if (context.mounted) {
                        MessageSendCubit messageSendCubit = context.read<MessageSendCubit>();
                        messageSendCubit.add(MessageSendSendMessageEvent(xFile.path, ImMessageType.Image));
                      }
                    }
                  },
                  child: buildSvgView('assets/svg/control.svg', 50, 50, Colors.white)
              ),
              GestureDetector(
                  onTap: () {},
                  child: buildSvgView('assets/svg/camera_reverse.svg', 50, 50, Colors.white)
              ),
            ],
          )
        ],
      ),
    );
  }

  // 拍照或摄影切换面板
  Widget _buildImageAndVideoSwitchPane() {
    return Padding(padding: const EdgeInsets.only(bottom: 20, right: 30), child: Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        GestureDetector(
            onTap: () {
              setState(() {
                _isCaptureImage = true;
              });
            },
            child: const Text('拍照', style: TextStyle(color: Colors.white),)
        ),
        const SizedBox(width: 30,),
        GestureDetector(
            onTap: () {
              setState(() {
                _isCaptureImage = false;
              });
            },
            child: const Text('摄像', style: TextStyle(color: Colors.white))
        ),
        const SizedBox(width: 30,),
        if (_isCaptureImage)
          const SizedBox(width: 20,),
        if (!_isCaptureImage)
          GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: buildSvgView('assets/svg/stop.svg', 20, 20, Colors.white)
          )
      ],),);
  }

  void _initCamera() {
    if (ImSingleton.getInstance().cameras.isNotEmpty) {
      _cameraController = CameraController(ImSingleton.getInstance().cameras[0], ResolutionPreset.medium); // 使用第一个相机，并设置分辨率
      _cameraController!.initialize().then((_) {
        if (!mounted) {
          return;
        }
        setState(() {
          _cameraInitialized = true;
        }); // 更新UI以显示相机预览
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
    _cameraController?.dispose(); // 释放相机资源
  }
}
